package Servlet;

/**
 * Created by 2015302580057 on 2017/7/12.
 */
import dao.UserDao;
import daoImpl.UserDaoImpl;
import entity.User;
import org.json.JSONObject;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.imageio.ImageIO;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;
import java.util.Random;


@WebServlet(name = "SendEmail",urlPatterns = {"/SendEmail"})
public class SendEmailServlet extends HttpServlet {

    public static final int WIDTH = 300; // 生成的图片的宽度
    public static final int HEIGHT = 45; // 生成的图片的高度

    //存储产生的数字
    private String checknum = "";


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String email = request.getParameter("myemail");

        UserDao dao = new UserDaoImpl();
        User u = dao.queryUserByEmail(email);

        PrintWriter pw = response.getWriter();
        JSONObject object = new JSONObject();//定义一个json对象，用来存储执行返回结果
        if (u != null){
            sendEmail(email);
            request.getSession().setAttribute("checknum",getChecknum());
            object.put("code",0);//成功
            pw.print(object);
        }else {
            object.put("code",1);//用户不存在
            pw.print(object);
        }

//        String password = request.getParameter("password");

//        response.setContentType("text/json;charset=utf-8");
//
//        UserDao dao = new UserDaoImpl();
//        User u = dao.queryUserByEmail(email);
//
//        PrintWriter pw = response.getWriter();
//        JSONObject object = new JSONObject();//定义一个json对象，用来存储执行返回结果，0代表成功，1代表用户已存在，2代表添加失败
//        if (u!=null){
//            u.setPassword(password);//设置新密码
//            int row = dao.updateUserPassword(u);//更新该用户的密码
//            if (row==1){
//                object.put("code",0);//修改成功
//                pw.print(object);
//            }else {
//                object.put("code",2);//出现了奇怪的错误
//                pw.print(object);
//            }
//
//        }else {
//                object.put("code",1);//用户不存在
//                pw.print(object);
//        }
//
//        pw.close();



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request,response);
    }

    //发送邮件的函数
    private boolean sendEmail(String address) throws IOException {
        //先创建一个验证码，再将其发送
        createCheckCode();

        Properties props = System.getProperties();
        props.put("mail.smtp.host","smtp.163.com");
        props.put("mail.smtp.auth","true");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("giggle_project@163.com","giggle163");
            }
        });
        try{
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("giggle_project@163.com"));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(address));
            message.setSubject("回复王孟老师");

            MimeMultipart allPart = new MimeMultipart("related");
            // first part  (the html)
            BodyPart messageBodyPart = new MimeBodyPart();
            String htmlContent = "<h1>老师好，这是我的作业<h2><br><img src=\"cid:image\">";
            messageBodyPart.setContent(htmlContent,"text/html");
            // add it
            allPart.addBodyPart(messageBodyPart);
            // second part (the image)
            messageBodyPart = new MimeBodyPart();
            DataSource fds = new FileDataSource("D:\\RichardProject\\giggle\\web\\img\\checknum.jpeg");
            messageBodyPart.setDataHandler(new DataHandler(fds));
            messageBodyPart.setHeader("Content-ID","<image>");
            // add it
            allPart.addBodyPart(messageBodyPart);

           //allPart.addBodyPart(contentpart);
            message.setContent(allPart);
            message.setSentDate(new Date());
            message.saveChanges();

            Transport.send(message);
        } catch (MessagingException e){
            e.printStackTrace();
            return false;
        }
        catch (java.lang.Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //创建验证码图片
    private void createCheckCode() throws IOException {
        //存储产生的图片
        Graphics g=null;

        // 在内存中创建一张图片
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        // 得到图片
        g = image.getGraphics();

        // 设置颜色
        g.setColor(Color.WHITE);
        // 填充区域
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 设置颜色
        g.setColor(Color.RED);
        // 设置字体
        g.setFont(new Font("宋体", Font.BOLD, 36));
        //产生0123456789之中的随机数
        String base = "0123456789";
        StringBuffer sb = new StringBuffer();
        int x = 5;
        // 控制字数
        for(int i=0;i<4;i++) {

            String ch = base.charAt(new Random().nextInt(base.length()))+"";
            sb.append(ch);
            g.drawString(ch, x,36);
            x+=75;
        }

        checknum = sb.toString();
        ImageIO.write(image,"jpeg",new File("D:\\RichardProject\\giggle\\web\\img\\checknum.jpeg"));

    }

    //获取产生的验证码
    public String getChecknum(){
        return checknum;
    }
}
